//
//  YTFPublishViewController.swift
//  sinaWeibo
//
//  Created by pro on 16/3/6.
//  Copyright © 2016年 pro. All rights reserved.
//

import UIKit
import SnapKit

let holderStr = "你特么不说点什么？？? ！！！"


class YTFPublishViewController: UIViewController ,UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    //定义一个约束来记录toolbar的底部约束
    var bottomConstraint: Constraint?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupNAV()
        
        setupTextView()
        
        setupToolBar()
        
        
        //添加键盘通知,对键盘frame的即将改变进行监听
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeToolBarFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "inputEmotionInTextView:", name: kNotificationEmotionTransform, object: nil)
    }
    
    //设置导航栏
    private func setupNAV(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "publish")
        
        //默认“发布”不可点击
        navigationItem.rightBarButtonItem?.enabled = false
        
        //设置title
//        navigationItem.title = "发布微博\n\(YTFUserViewModel.shareInstance.model?.screen_name)"
        //自定义一个label
        let titleLabel = UILabel(frame: CGRectMake(0,0,200,44))
        
        //设置换行
        titleLabel.numberOfLines = 0
        
        //设置居中
        titleLabel.textAlignment = .Center
        
        //label内部文字
        let str = "发布微博\n\(YTFUserViewModel.shareInstance.model?.screen_name ?? "")"
        
        //为字符串设置属性
        //NSAttributedString不可变，修改属性需要使用可变的NSMutableAttributedString
        let attribute = NSMutableAttributedString(string: str)
        
        //添加属性
        //修改 “发布微博” 4个字的属性
        attribute.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(15)], range: NSMakeRange(0, 4))
        
        //修改昵称属性
        attribute.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(13),NSForegroundColorAttributeName: UIColor.orangeColor()], range: NSMakeRange(4, str.characters.count - 4))
        
        //添加到label上
        titleLabel.attributedText = attribute
        
        //将这个label设置为navigationItem的titleView
        navigationItem.titleView = titleLabel
        
    }
    
    
    //设置toolbar
    private func setupToolBar(){
        
        //设置toolbar的颜色
        toolBar.backgroundColor = UIColor.lightGrayColor()
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        //定义一个数组，来接收items
        var items = [UIBarButtonItem]()
        
        for setting in itemSettings {
            
            //自定义一个button
            let button = UIButton(type: UIButtonType.Custom)
            
            //设置button的属性和方法
            let str = setting["imageName"]!
            button.setImage(UIImage(named: str), forState: UIControlState.Normal)
            
            //设置高亮状态
            button.setImage(UIImage(named: "\(str)_highlighted"), forState: UIControlState.Highlighted)
            
            //设置button的大小
            button.sizeToFit()
            
            //添加方法
            if let action = setting["action"] {
                
                //添加方法
                //注意一个问题，当添加方法的时候，使用“xxxx”，不代表里面是字符串
                button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
                
            }
            
            //赋值给UIBarButtonItem
            let item = UIBarButtonItem(customView: button)
            
            //把item添加到数组中
            items.append(item)
            
            //添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        //这样就得到一个item的数组，但是最后还多一个弹簧
        items.removeLast()
        
        //添加到toolbar上
        toolBar.items = items
        
        //把toolbar添加到视图上
        view.addSubview(toolBar)
        
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(40)
            bottomConstraint = make.bottom.equalTo(view.snp_bottom).constraint
            
        }
        
    }
    

    
    @objc private func choosePicture(){
//        print("选择图片")
        //第一步，判断能否访问相册
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            
            //实例化一个UIImagePickerController
            let picker = UIImagePickerController()
            
            //设置类型,更具需要访问的决定
            picker.sourceType = .PhotoLibrary
            
            //设置代理
            picker.delegate = self
            
            //允许访问相册，进行页面跳转
            presentViewController(picker, animated: true, completion: { () -> Void in
                
            })
        }
        
    }
    
    @objc private func inputEmoticon(){
        print("显示表情")
        
        //inputView在nil的时候显示的是键盘，要更改键盘的视图需要修改键盘的inputView
        
        //先注销第一响应者，在改变键盘的视图
        textView.resignFirstResponder()
        
        //判断键盘的状态，来实现点击表情按钮的时候实现键盘视图的切换
        if textView.inputView == nil{
        
            textView.inputView = emotionView
        }else{
            textView.inputView = nil
        }
        
        //成为第一响应者
        textView.becomeFirstResponder()
        
    }
    
    //返回的点击事件
    //为什么需要添加@objc
    @objc private func dismiss(){
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    //发布的点击事件
    @objc private func publish(){
        print("发布")
    }
    
    
    //MARK: -- 键盘改变的通知
    func changeToolBarFrame(noti: NSNotification){
        
        if let info = noti.userInfo {
            
            //获取高度
            let endFrame = info[UIKeyboardFrameEndUserInfoKey]?.CGRectValue
            
            //获取时间,即键盘上升和下降的时间
            let duration = info[UIKeyboardAnimationDurationUserInfoKey]?.doubleValue
            
//            清空约束
            bottomConstraint?.uninstall()
            
//            if endFrame?.origin.y == kUIScreenHeight{
////            if endFrame?.origin.y < (kUIScreenHeight - 271){
//            
//                //键盘退出状态
//                print("退出键盘")
//                
////            跟新约束
//                toolBar.snp_updateConstraints(closure: { (make) -> Void in
//                    bottomConstraint = make.bottom.equalTo(view.snp_bottom).constraint
//                })
//                
//            }else{
//                //键盘弹出状态
//                print("弹出键盘")
//                
////                //更新约束
//                toolBar.snp_updateConstraints(closure: { (make) -> Void in
//                    bottomConstraint = make.bottom.equalTo(view.snp_bottom).offset(-271).constraint
//                })
//                
//            }
            //更新约束
            toolBar.snp_updateConstraints(closure: { (make) -> Void in
                bottomConstraint = make.bottom.equalTo(view.snp_bottom).offset(endFrame?.origin.y == kUIScreenHeight ? 0 : -endFrame!.height).constraint
            })
            
            //添加动画
            UIView.animateWithDuration(duration!, animations: { () -> Void in
                //重新布局
                self.toolBar.layoutIfNeeded()
            })
           
        }
    
    }
    
    //MARK: -- 在输入框中插入表情
    @objc private func inputEmotionInTextView(noti: NSNotification){
        
        //获取表情
        let emotion = noti.userInfo!["emotion"] as! YTFEmotion
        
//        print(emotion.chs)
        //判断图片是否有值
        if let png = emotion.png {
            
            //定义一个可变的oldAttributedText来存放之前的AttributedText
            let oldAttributedText = NSMutableAttributedString(attributedString: textView.attributedText)
            
            //创建一个附件
            let attachment = YTFTextAttachment()
            
            //给属性赋值
            attachment.emotion = emotion
            
            //凭借图片路径
            let imagePath = "\(emotion.path!)/\(png)"
    
            //获取图片
            let image = UIImage(named: imagePath)
            
            //设置attachment的图片属性
            attachment.image = image
            
            //赋值给attribute
            let attribute = NSAttributedString(attachment: attachment)
            
            //寻找光标的位置
            let range = textView.selectedRange
            
            //拼接NSAttributedString并赋值给oldAttributedText
            oldAttributedText.insertAttributedString(attribute, atIndex: range.location)
            
            textView.attributedText = oldAttributedText
            
            //重新定位光标位置
            textView.selectedRange = NSMakeRange(range.location+1, 0)
        }
        
        if let emoji = emotion.emoji{
            
            let oldAttributedText = NSMutableAttributedString(attributedString: textView.attributedText)
            
            let range = textView.selectedRange
            
            //拼接
            oldAttributedText.replaceCharactersInRange(NSMakeRange(range.location, 0), withString: emoji)
            
            textView.attributedText = oldAttributedText
            
            //重新定位光标
            textView.selectedRange = NSMakeRange(range.location+1, 0)
            
        }
        
        
    }
    
    
    //移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillChangeFrameNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: kNotificationEmotionTransform, object: nil)
        print("控制器销毁")
    }
    
    //UITextField不能换行，但能设置暗文
    //UITextView能换行，但不能设置暗文，这里我们选择UITextView，暗文采用画上去的方式实现
    //设置texrView
    private func setupTextView(){
        
        //添加视图
        view.addSubview(textView)
        
        //设置约束
        textView.frame = view.frame
        
        //设置暗文
        textView.holderString = holderStr
        
        textView.font = UIFont.systemFontOfSize(15)
        
        //设置代理
        textView.delegate = self
        
        //滑动textView，让键盘消失
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = .OnDrag
        
        //添加控件，添加在textView上
        textView.addSubview(photoView)
        
        //设置约束
        photoView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(textView.snp_center)
            make.width.equalTo(kUIScreenWidth - 2 * photoViewMargin)
            make.height.equalTo(photoView.snp_width)
        }
        
    }
    
    
    //MARK: -- 懒加载
    private lazy var textView: YTFTextView = YTFTextView()
    
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    private lazy var photoView: YTFPhotoView = {
        
        let photo = YTFPhotoView()
        
        //为避免闭包的循环引用，使用如下方法
        photo.closure = {[weak self] () -> () in
            
            //调用选择图片的方法
            self?.choosePicture()
        
        }
        
        return photo
    }()

    private lazy var emotionView: YTFEmotionView = {
        
        let emotionView = YTFEmotionView()
        
        emotionView.frame.size = CGSizeMake(kUIScreenWidth,217)
        
        emotionView.backgroundColor = UIColor.greenColor()
        
        return emotionView
    }()
}


//MARK: --UIImagePickerControllerDelegate和UINavigationControllerDelegate的代理方法
extension YTFPublishViewController {
    
    //选择相册获取图片
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //将图片添加到photoView的数组中
        photoView.addImage(image)
        
        //添加图片完成之后就退回上一个控制器,这里需要手动跳转
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }

}


//MARK:-- UITextVie的代理方法
extension YTFPublishViewController {

    func textViewDidChange(textView: UITextView) {
        
        if textView.hasText(){
            
            //不显示占位符
            self.textView.holderString = ""
            
        }else {
            
            //显示占位符
            self.textView.holderString = holderStr
        }
        
        //修改了画的内容，需要重绘一下
        self.textView.setNeedsDisplay()
        
        //“发布”按钮的状态与是textView是否有值相一致
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
    
}


